package com.pic4493.app;

import java.util.ArrayList;

import org.json.JSONArray;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.pic4493.adapter.AdpList_Favorites;
import com.pic4493.adapter.AdpList_PicList;
import com.pic4493.base.BaseUITopBar;
import com.pic4493.comm.PubConst;
import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.EAlbum;
import com.pic4493.entities.EPhoto;
import com.pic4493.net.NetClientJ;
import com.pic4493.utils.UtiDialog;
import com.ppcodes.imageloader.core.DisplayImageOptions;
import com.ppcodes.imageloader.core.ImageLoader;
import com.ppcodes.imageloader.core.assist.FailReason;
import com.ppcodes.imageloader.core.assist.ImageLoadingListener;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshBase;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.ppcodes.views.pulltorefresh.library.PullToRefreshBase.Mode;
import com.ppcodes.views.staggeredgridview.StaggeredGridView;

public class UIFavorites extends BaseUITopBar
{
   private PullToRefreshStaggeredGridView mGridView;
   private LayoutInflater mInflater;
   private int mCurrentIndex = 1;
   private int mPageCount;
   private ArrayList<Integer> mLoadedIndex;
   private boolean mIsPullToRefresh = false;

   private ArrayList<EPhoto> mList;
   private AdpList_Favorites mAdpFav;

   private void initView()
   {
	  mInflater = LayoutInflater.from(mContext);
	  mGridView = (PullToRefreshStaggeredGridView) findViewById(R.id.uifav_list);
	  View footView = mInflater.inflate(R.layout.layout_loading_footer, null);// 加载时显示的
	  mGridView.getRefreshableView().setFooterView(footView);
	  mGridView.getRefreshableView().setColumnCount(2);
	  mGridView.setMode(Mode.PULL_FROM_START);
   }

   private void initEvent()
   {

	  // 下拉触发的事件
	  mGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<StaggeredGridView>()
	  {
		 @Override
		 public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView)
		 {
			mIsPullToRefresh = true;
			initData();
		 }
	  });
	  // 滑到最下面加载更多数据的事件
	  mGridView.setOnLoadmoreListener(new StaggeredGridView.OnLoadmoreListener()
	  {
		 @Override
		 public void onLoadmore()
		 {
			if (mCurrentIndex < mPageCount)
			{
			   loadMoreData();
			}
			else
			{
			   mGridView.onLoadComplete();
			   mAdpFav.notifyDataSetChanged();
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, "没有更多的数据了");
			}
		 }
	  });

	  mAdpFav = new AdpList_Favorites(mContext, new AdpList_Favorites.OnClickEvent()
	  {
		 @Override
		 public void Do(int position, View v)
		 {
			ImageLoader.getInstance().loadImage(mContext, ((EPhoto) mAdpFav.getItem(position)).getUrl(), new ImageLoadingListener()
			{
			   @Override
			   public void onLoadingStarted()
			   {
				  UtiDialog.getInstance().ShowLoadingDialogNoTitle(mContext, "请稍候...");
			   }

			   @Override
			   public void onLoadingFailed(FailReason failReason)
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "网络异常");
			   }

			   @Override
			   public void onLoadingComplete(Bitmap loadedImage)
			   {
				  UtiDialog.getInstance().DismissLoadingDialog();
				  Session.getInstance().picCache = loadedImage;
				  Intent intent = new Intent(mContext, UIPic.class);
				  startActivity(intent);
			   }

			   @Override
			   public void onLoadingCancelled()
			   {

			   }
			});
		 }
	  });
   }

   private void initData()
   {
	  mCurrentIndex = 1;
	  mAdpFav.cleanData();
	  mLoadedIndex = new ArrayList<Integer>();
	  executeAsyncTask("initData");
   }

   private void loadMoreData()
   {
	  mCurrentIndex++;
	  if (!isLoadedThisPage(mCurrentIndex))// 此页没有被加载过
	  {
		 executeAsyncTask("loadData");
	  }

   }

   private boolean isLoadedThisPage(int index)
   {
	  if (-1 == mLoadedIndex.indexOf(index))
	  {
		 return false;
	  }
	  else
	  {
		 return true;
	  }
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  setContentView(R.layout.uifav);
	  super.onCreate(savedInstanceState);
	  setTitle("我的收藏");
	  initView();
	  initEvent();
	  initData();
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  if ("initData".equals(taskName))
	  {
		 if (!mIsPullToRefresh)
		 {
			UtiDialog.getInstance().ShowLoadingDialogNoTitle(mContext, "加载中...");
		 }
	  }
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if ("loadData".equals(taskName) || "initData".equals(taskName))
	  {
		 return NetClientJ.GetUserFavorites(mCurrentIndex);
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  UtiDialog.getInstance().DismissLoadingDialog();
	  try
	  {
		 if (result != null)
		 {
			DJson data = (DJson) result;
			if (!data.getHead().hasError())
			{
			   if ("initData".equals(taskName) || "loadData".equals(taskName))
			   {
				  mPageCount = data.getHead().getPageCount();
				  JSONArray photos = data.getBody().optJSONArray("favorites");
				  if (photos != null && photos.length() > 0)
				  {
					 mList = new ArrayList<EPhoto>();
					 EPhoto photo = null;
					 for (int i = 0; i < photos.length(); i++)
					 {
						photo = new EPhoto();
						photo.setId(photos.optJSONObject(i).optString("pid"));
						photo.setUrl(photos.optJSONObject(i).optString("pic"));
						photo.setDate(photos.optJSONObject(i).optString("date"));
						photo.setThumbnailUrl(photos.optJSONObject(i).optString("thumbnail"));
						photo.setThumbnailHeight(photos.optJSONObject(i).optInt("thum_height", 0));
						photo.setThumbnailWidth(photos.optJSONObject(i).optInt("thum_width", 0));
						mList.add(photo);
					 }

					 mAdpFav.addItem(mList);
					 if ("initData".equals(taskName))
					 {
						mGridView.setAdapter(mAdpFav);
					 }
					 if (mPageCount == 1)// 如果只有一页数据,也不显示最下面的loading
					 {
						mGridView.onLoadComplete();
					 }
					 mAdpFav.notifyDataSetChanged();
					 mLoadedIndex.add(mCurrentIndex);// 将此页加入已读页码列表
				  }
				  else
				  {
					 if (mList.size() == 0)
					 {
						UtiDialog.getInstance().ShowToastInfoShort(mContext, "暂无数据");
						finish();
					 }
					 else
					 {
						mGridView.onLoadComplete();
						mAdpFav.notifyDataSetChanged();
						if (mAdpFav.getCount() == 0)
						{
						   UtiDialog.getInstance().ShowOKAlertDialogEX(mContext, "提示", "暂无数据", new DialogInterface.OnClickListener()
						   {
							  @Override
							  public void onClick(DialogInterface dialog, int which)
							  {
								 finish();
							  }
						   });
						}
					 }
				  }
				  if (mIsPullToRefresh)
				  {
					 mGridView.onRefreshComplete();
					 mIsPullToRefresh = false;
				  }
			   }
			}
			else
			{
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, data.getHead().getRspMsg());
			}
		 }
		 else
		 {
			UtiDialog.getInstance().ShowToastInfoShort(mContext, "网络异常请稍候再试");
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIFavorites_onAsyncTaskEnd(taskId, taskName, params, result) " + e);
	  }
   }

}
